package com.xudow.app.dynamicstate_old.data.server;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.jude.utils.JUtils;
import com.xudow.app.dynamicstate_old.domain.entity.Token;
import com.xudow.app.util.StringUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Iterator;
import java.util.ServiceConfigurationError;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Zane on 16/3/14.
 * 拦截,http缓存
 */
public class RestInterceptors implements Interceptor {

    private static final String TAG = "HeaderInterceptors";

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();

        Response originalResponse = chain.proceed(request);
        MediaType contentType = originalResponse.body().contentType();

        //先解析一遍json数据，根据status和message去手动改状态码和描述
        String originalContent = originalResponse.body().string();
        JUtils.Log("RestInterceptors", request.url().toString() + ":\n" + originalContent);

        int code = 400;
        int errorCode = 0;
        String errorMessage = "";
        String body = "null";
        String data = "";
        String resultLst = "";

        JSONObject wrapper = null;
        try {
            wrapper = new JSONObject(originalContent);
            Iterator<String> iterator = wrapper.keys();
            while (iterator.hasNext()) {
                String key = iterator.next();
                switch (key) {
                    case "result":
                        code = wrapper.getInt(key);
                        if (code == 0) code = 200;
                        else code = 400;
                        break;
                    case "errorCode":
                        errorMessage = wrapper.getString(key);
                        break;
                    case "errorMessage":
                        errorMessage = wrapper.getString(key);
                        break;
                    case "data":
                        data = wrapper.getString(key);
                        break;
                    case "resultLst":
                        resultLst = wrapper.getString(key);
                        break;
                    case "advInfoList":
                        resultLst = wrapper.getString(key);
                        break;
                    case "allSize":
                        break;
                    default:
                        body = wrapper.getString(key);
                        break;
                }
            }

            if (body.startsWith("{") || body.startsWith("[")) {
                //这应该就是真是数据
                //这样子会是坑的
                if (!StringUtils.isEmpty(data)) {
                    StringBuilder sb = new StringBuilder();
                    body = sb.append("{").append("'data':").append(data).append(",").append("'mainData':").append(body).append("}").toString();
                }
            } else if (TextUtils.isEmpty(data)) body = resultLst;//照尿性讲,没有data就一定是resultLst
            else if (TextUtils.isEmpty(resultLst)) body = data;
            else if (data.equals("null") && !resultLst.equals("[]")) body = resultLst;
            else if (!data.equals("null") && resultLst.equals("[]")) body = data;
        } catch (JSONException e) {
            throw new ServiceConfigurationError("服务器错误：" + e.getLocalizedMessage());
        }

        //七牛token包含特殊字符,是返回纯String。Gson会SB。
        if (request.url().toString().contains("qiniu")) {
            body = new Gson().toJson(new Token(body));
        }

        return originalResponse.newBuilder()
                .code(code)
                .message(errorMessage)
                .body(ResponseBody.create(contentType, body))
                .build();

    }
}
